﻿using Ingr.Yu;
using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Xml.Linq;

namespace PlotDrawFromSha
{
    public partial class PlotDrawingFrom3D : Form
    {

        /// <summary>
        /// 绘制的主要逻辑
        /// </summary>
        Plot x;

        /// <summary>
        /// 用于从外界接收参数
        /// </summary>
        public PID PIDDBConn;
        public Llama.LMADataSource DS;
        public PlotDrawingFrom3D()
        {
            InitializeComponent();
            x = new Plot();
            DS = x.DS;
            if (PIDDBConn == null)
            {
                PIDDBConn = new PID();
                PIDDBConn.PlantName = DS.ProjectNumber;
                //        x.PIDDBConn.PlantName = DS.ProjectNumber
                PIDDBConn.ReadUserAndPs_in_Ini(DS.get_SiteNode());
                PIDDBConn.ConnPID_admin(PIDDBConn.PIDIniDBType, PIDDBConn.PIDSite_Server, PIDDBConn.PIDSite_DBNAME, PIDDBConn.PIDDBSystemUser, PIDDBConn.PIDDBSystemPs);

            }
            this.label7.Text = x.symbolRootPath;
        }
        /// <summary>
        /// 执行按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            System.Windows.MessageBox.Show("该功能需要配合PID主程序（draft.exe）。确保您已经保存了正在编辑中的图纸。因为程序运行时，将会关闭一次pid的主程序。");

            System.Windows.MessageBox.Show("由于需要绘制OPC，所以需要事先勾选PID - Tools - Options - Placement中的“Place partner OPC in stockpile”。");
            if (x.folderPath != "")
            {
                if (!System.IO.File.Exists(textBox_ConfigPath.Text))
                {
                    System.Windows.MessageBox.Show("请选择有效的路径。");
                    textBox_ConfigPath.BackColor = Color.Red;

                }

                else
                {
                    try
                    {
                        if (initSymbolInfo())
                        {
                            //if (CompareSymbolInfoWithXml())
                            //{
                            double density, index;
                            if (!double.TryParse(this.textBox_Grid_Density.Text, out density))
                            {
                                System.Windows.MessageBox.Show("Grid密度中，请输入有效的数字。");
                            }
                            if (!double.TryParse(this.textBox_Grid_Index.Text, out index))
                            {
                                System.Windows.MessageBox.Show("Grid Index中，请输入有效的数字。");
                            }
                            x.StartPlot(checkBox_PlotMode.Checked ? Plot.PlotMode.OnExisted : Plot.PlotMode.New,
                                density * index / 1000,
                                this.checkBox_PIDAppVisible.Checked,
                                this.checkBox_Label_引线.Checked, PIDDBConn);
                            //}

                        }
                    }
                    catch (Exception e2)
                    {
                        System.Windows.MessageBox.Show(e2.Message);

                    }



                }
            }
            else
            {
                System.Windows.MessageBox.Show("请选择S3D解析出来的xml的文件夹。");
            }

        }
        /// <summary>
        /// 比较配置文件里的symb和所有3D生成的xml之间的差异
        /// </summary>
        /// <returns></returns>
        //public bool CompareSymbolInfoWithXml()
        //{
        //    //List<string> NotMappingType = new List<string>();
        //    x.symbolInfoNotMapped.Clear();
        //    //StringBuilder missingSymbol = new StringBuilder();
        //    if (System.IO.Directory.Exists(x.folderPath))
        //    {
        //        var xmlFolder = new DirectoryInfo(x.folderPath);
        //        foreach (var xmlFile in xmlFolder.EnumerateFiles("*.xml"))
        //        {
        //            if (System.IO.File.Exists(xmlFile.FullName))
        //            {
        //                var xDoc = XDocument.Load(xmlFile.FullName);
        //                if (xDoc != null)
        //                {
        //                    var xRoot = xDoc.Root;
        //                    IEnumerable<XElement> RouteCol = xRoot.Elements("Route");//每个xml里的所有piperun
        //                    foreach (XElement route in RouteCol)
        //                    {
        //                        //route下面就是Parts和Branchs
        //                        //Parts节点的shortCode属性里分：固定的列表（如PIPE、FLOW、OPC、ST），以及更多动态的类别（如gate valve、blind flange、ins spe等）
        //                        foreach (var partNode in route.Elements().Where(x => x.Name.ToString().ToUpper() == "Parts".ToUpper()))
        //                        {
        //                            var type = partNode.Attribute("ShortCode").Value.ToUpper();
        //                            if (!x.symbolInfo.Any(x => x.shortCode.ToUpper() == type) && type != Global.const_PipeShortCode && !x.symbolInfoNotMapped.Any(x => x.shortCode == type))
        //                            {
        //                                x.symbolInfoNotMapped.Add(new SymInfo() { shortCode = type, symPath = partNode.Value, shortType = symType.未定义 });
        //                                //NotMappingType.Add(type);//图纸xml中，存在配置文件里不存在的类型
        //                            }
        //                        }
        //                    }

        //                }
        //            }
        //        }
        //    }

        //    //if (NotMappingType.Count > 0)
        //    //{
        //    //    string res = "";
        //    //    foreach (var item in NotMappingType)
        //    //    {
        //    //        res += item + ",";
        //    //    }
        //    //    System.Windows.MessageBox.Show("xml中，检查到配置文件中不存在的图例。" + "\r\n" + $"缺少以下shortCode的图例配置:{res}" + "\r\n" + "请检查下。");
        //    //    return false;
        //    //}
        //    //else
        //    //{
        //    return true;
        //    //}
        //}
        /// <summary>
        /// 从配置文件中初始化图例和属性信息。写入2个集合list。
        /// </summary>
        public bool initSymbolInfo()
        {
            x.symbolInfo.Clear();
            x.attributeInfos.Clear();
            ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook(x.ConfigPath);
            if (wb != null)
            {
                ClosedXML.Excel.IXLWorksheet ws = wb.Worksheet("symbol");
                #region SYM
                if (ws != null)
                {
                    int MaxRow = ws.LastRowUsed().RowNumber();
                    StringBuilder missingSymbol = new StringBuilder();//代表配置文件中，路径不正确的symbol记录
                    StringBuilder duplicateSymbol = new StringBuilder();//代表配置文件中，重复的symbol记录
                    for (int i = 1; i < MaxRow; i++)
                    {
                        string symbolName = ws.Cell(i + 1, 1).Value.ToString();
                        string symbolPath = ws.Cell(i + 1, 2).Value.ToString();
                        string symType = ws.Cell(i + 1, 3).Value.ToString();
                        string symLen = ws.Cell(i + 1, 4).Value.ToString();
                        double symLenValue;

                        if (double.TryParse(symLen, out symLenValue))
                        {

                        }
                        else
                        {
                            symLenValue = 0.00762;
                        }

                        symType parsedsymType;

                        if (Enum.TryParse<symType>(symType, out parsedsymType))
                        {
                            // 字符串成功转换为枚举值 
                        }
                        else
                        {
                            // 字符串无法转换为有效的枚举值
                            continue;
                        }

                        if (string.IsNullOrEmpty(symbolName))
                        {
                            continue;
                        }

                        //symbolName = item.Attribute("SymbolName").Value;
                        //symbolPath = item.Attribute("FileName").Value.GetPath(new DirectoryInfo(symbolRootPath));
                        if (!x.symbolInfo.Any(x => x.shortCode == symbolName)) //(!symbolInfo.ContainsKey(symbolName))
                        {
                            if (File.Exists(x.symbolRootPath + symbolPath))
                            {
                                x.symbolInfo.Add(new SymInfo() { SymLen = symLenValue, shortCode = symbolName, symPath = x.symbolRootPath + symbolPath, shortType = parsedsymType });
                            }
                            else if (File.Exists(x.symbolRootPath + "\\" + symbolPath))//excel里原本少里一个\符号
                            {
                                x.symbolInfo.Add(new SymInfo() { SymLen = symLenValue, shortCode = symbolName, symPath = x.symbolRootPath + "\\" + symbolPath, shortType = parsedsymType });
                            }
                            else
                            {
                                missingSymbol.Append($"{symbolName}\n");
                            }
                        }
                        else
                        {
                            duplicateSymbol.Append($"{symbolName}\n");
                        }


                    }
                    if (duplicateSymbol.Length + missingSymbol.Length > 0)
                    {
                        System.Windows.MessageBox.Show($"图例重复配置：{duplicateSymbol}" + "\r\n" + $"无效的图例：{missingSymbol}" + "\r\n" + "请去检查下图例配置文件。", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return false;
                    }
                    else
                    {

                        #region  检查几个必要的SYMBOL和label是否存在。
                        if (!x.symbolInfo.Any(x => x.shortCode.ToUpper() == "MainRunLabel".ToUpper()))
                        {
                            System.Windows.MessageBox.Show($"A列未找到必要的MainRunLabel。请检查下。");
                            return false;
                        }
                        if (!x.symbolInfo.Any(x => x.shortCode.ToUpper() == "MainRun".ToUpper() || x.shortCode.ToUpper() == Global.const_PipeShortCode))
                        {
                            System.Windows.MessageBox.Show($"A列未找到必要的MainRun。请检查下。");
                            return false;
                        }
                        if (!x.symbolInfo.Any(x => x.shortCode.ToUpper() == "EndOfGroup".ToUpper()))
                        {
                            System.Windows.MessageBox.Show($"A列未找到必要的EndOfGroup。请检查下。");
                            return false;
                        }
                        if (!x.symbolInfo.Any(x => x.shortCode.ToUpper() == "ChangeSizeLabel".ToUpper()))
                        {
                            System.Windows.MessageBox.Show($"A列未找到必要的ChangeSizeLabel。请检查下。");
                            return false;
                        }
                        if (!x.symbolInfo.Any(x => x.shortCode.ToUpper() == Global.const_OPCShortCode))
                        {
                            System.Windows.MessageBox.Show($"A列未找到必要的OPC。请检查下。");
                            return false;
                        }
                        if (!x.symbolInfo.Any(x => x.shortCode.ToUpper() == Global.const_FlowShortCode))
                        {
                            System.Windows.MessageBox.Show($"A列未找到必要的FLOW。请检查下。");
                            return false;
                        }
                        if (!x.symbolInfo.Any(x => x.shortCode.ToUpper() == Global.const_STShortCode))
                        {
                            System.Windows.MessageBox.Show($"A列未找到必要的疏水阀。请检查下。");
                            return false;
                        }
                        if (!x.symbolInfo.Any(x => x.shortCode.ToUpper() == "NOTFOUND"))
                        {
                            System.Windows.MessageBox.Show($"A列未找到必要的NOTFOUND。请检查下。");
                            return false;
                        }
                        if (!x.symbolInfo.Any(x => x.shortCode.ToUpper() == "PAIREDFLANGE"))
                        {
                            System.Windows.MessageBox.Show($"A列未找到必要的PairedFlange。请检查下。");
                            return false;
                        }

                        x.locMainRunLabel = x.symbolInfo.FirstOrDefault(x => x.shortCode.ToUpper() == "MainRunLabel".ToUpper())?.symPath;
                        x.locMainRun = x.symbolInfo.FirstOrDefault(x => x.shortCode.ToUpper() == "MainRun".ToUpper() || x.shortCode.ToUpper() == Global.const_PipeShortCode)?.symPath;
                        x.locEndOfGroup = x.symbolInfo.FirstOrDefault(x => x.shortCode.ToUpper() == "EndOfGroup".ToUpper())?.symPath;
                        x.locChangeSizeLabel = x.symbolInfo.FirstOrDefault(x => x.shortCode.ToUpper() == "ChangeSizeLabel".ToUpper())?.symPath;
                        x.locOPC = x.symbolInfo.FirstOrDefault(x => x.shortCode.ToUpper() == Global.const_OPCShortCode)?.symPath;
                        x.locFlow = x.symbolInfo.FirstOrDefault(x => x.shortCode.ToUpper() == Global.const_FlowShortCode)?.symPath;
                        x.locST = x.symbolInfo.FirstOrDefault(x => x.shortCode.ToUpper() == Global.const_STShortCode)?.symPath;
                        x.locNotFound = x.symbolInfo.FirstOrDefault(x => x.shortCode.ToUpper() == "NOTFOUND")?.symPath;
                        x.locPairedFlange = x.symbolInfo.FirstOrDefault(x => x.shortCode.ToUpper() == "PAIREDFLANGE")?.symPath;
                        #endregion
                    }
                }
                else
                {
                    System.Windows.MessageBox.Show($"{x.ConfigPath}的内容不符合要求，没找到名为symbol的页。请检查下。");
                    return false;
                }
                #endregion
                #region ATTR
                ws = wb.Worksheet("attribute");
                if (ws != null)
                {
                    StringBuilder missingSymbol = new StringBuilder();
                    StringBuilder duplicateSymbol = new StringBuilder();
                    DataTable dt = new DataTable();
                    string sql = "select * from xxxSchemaName.itemattributions t where t.itemid = '4'";
                    var res = PIDDBConn.PIDReadDataByDBA(PIDDBConn.PIDPlant_DBNAME, PIDDBConn.ActivePlantPIDAppDictionary_User, sql, out dt);
                    if (res != "")
                    {
                        System.Windows.MessageBox.Show($"以用户{ PIDDBConn.ActivePlantPIDAppDictionary_User}查询PID数据库时遇到问题。{res}");
                        return false;
                    }
                    int MaxRow = ws.LastRowUsed().RowNumber();
                    StringBuilder invalidAttr = new StringBuilder();
                    for (int i = 1; i < MaxRow; i++)
                    {
                        string xmlAttr = ws.Cell(i + 1, 1).Value.ToString();
                        string pidAttr = ws.Cell(i + 1, 2).Value.ToString().ToUpper();
                        DataRow dr = dt.AsEnumerable().FirstOrDefault(x => x["name"].ToString().ToUpper() == pidAttr || x["displayname"].ToString().ToUpper() == pidAttr);
                        if (dr != null)
                        {
                            if (!x.attributeInfos.Any(x => x.Value == dr["name"].ToString()))
                            {
                                x.attributeInfos.Add(xmlAttr, dr["name"].ToString());
                            }
                            else
                            {
                                duplicateSymbol.Append($"{xmlAttr}\n");
                            }
                        }
                        else
                        {
                            missingSymbol.Append($"{xmlAttr}\n");
                        }
                    }
                    if (x.attributeInfos.Any(x => x.Value.ToUpper() == "ITEMTAG"))
                    {
                        var ItemTagInXml = x.attributeInfos.FirstOrDefault(x => x.Value.ToUpper() == "ITEMTAG");
                        x.attributeInfos.Remove(ItemTagInXml.Key);
                        x.ItemTagAttrInfo = new Tuple<string, string>(ItemTagInXml.Key, ItemTagInXml.Value);
                    }
                    else
                    {
                        //2023 05 05, 陈玉娟，不需要 itemtag，因为有专门的itemtag.dll去进行触发
                        //System.Windows.MessageBox.Show($"{x.configPath}的attribute页中，在 B列 没找到必要的ItemTag属性。请检查下。");
                        //return false;
                    }
                    if (duplicateSymbol.Length + missingSymbol.Length > 0)
                    {
                        System.Windows.MessageBox.Show($"属性重复配置：{duplicateSymbol}" + "\r\n" + $"无效的属性：{missingSymbol}" + "\r\n" + "请去检查下配置文件。", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return false;
                    }
                }
                else
                {
                    System.Windows.MessageBox.Show($"{x.ConfigPath}的内容不符合要求，没找到名为attribute的页。请检查下。");
                    return false;
                }
                #endregion
                return true;
            }
            else
            {
                System.Windows.MessageBox.Show($"{x.ConfigPath}找不到。请检查下。");
                return false;
            }

            //    '定义excel相关对象
            //Dim MyWB As ClosedXML.Excel.XLWorkbook
            //'Dim MySheet As ClosedXML.Excel.IXLWorksheet

            //MyWB = New ClosedXML.Excel.XLWorkbook()
            //MyWB.AddWorksheet(dtCreate, "蓝撇报告")

        }
        /// <summary>
        /// xml文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            CommonOpenFileDialog dialog = new CommonOpenFileDialog();
            DialogResult FolderOrFileDialog = System.Windows.Forms.MessageBox.Show("选择文件夹（选Yes）还是单个文件（选No）？", "1", MessageBoxButtons.YesNoCancel);
            switch (FolderOrFileDialog)
            {
                case DialogResult.Yes:
                    //文件夹
                    dialog.IsFolderPicker = true;
                    x.folderOrFile = true;
                    break;
                case DialogResult.No:
                    //文件
                    dialog.Filters.Add(new CommonFileDialogFilter("XML Files Output From S3D", ".xml"));

                    dialog.IsFolderPicker = false;
                    x.folderOrFile = false;
                    break;

                case DialogResult.None:
                case DialogResult.OK:
                case DialogResult.Cancel:
                case DialogResult.Abort:
                case DialogResult.Retry:
                case DialogResult.Ignore:
                default:
                    return;
                    break;
            }


            if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                x.folderPath = dialog.FileName;
                textBox_XMLFolder.Text = x.folderPath;

            }
            else
            {
                x.folderPath = "";
            }

        }


        /// <summary>
        /// 启动时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PlotDrawingFrom3D_Load(object sender, EventArgs e)
        {
            this.Text = "根据来自S3D的xml文件，自动绘制简易的PID图纸。。。" + System.IO.File.GetLastWriteTime(this.GetType().Assembly.Location);
            x.ConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "配置文件", "阀门图例对应关系.xlsx");// "SymMapping.config.xml");
            this.textBox_ConfigPath.Text = x.ConfigPath;
        }
        /// <summary>
        /// 配置文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click_1(object sender, EventArgs e)
        {
            CommonOpenFileDialog dialog = new CommonOpenFileDialog();
            dialog.DefaultExtension = ".xlsx";
            dialog.InitialDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "配置文件");
            dialog.EnsurePathExists = true;
            dialog.Multiselect = false;
            dialog.EnsureValidNames = true;
            if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                x.ConfigPath = dialog.FileName;
                textBox_ConfigPath.Text = dialog.FileName;
                if (System.IO.File.Exists(dialog.FileName))
                {
                    textBox_ConfigPath.BackColor = Color.ForestGreen;
                }
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void checkBox_Label_引线_CheckedChanged(object sender, EventArgs e)
        {

        }
    }

}
